<template>
  <div class="good-container">
    <Row class="margin-top-10">
      <i-col span="24">
        <Card>
          <p class="title" slot="title">
            商品管理
            <Button class="add-icon" type="primary" icon="android-add" @click="handleAdd">新增商品</Button>
          </p>
          <p class="find" style="margin-bottom: 20px;">
            书籍名或者作者名
            <i-input
              style="display: inline-block; width: 200px; margin-left: 20px; margin-right: 20px"
              v-model="searchName"
              placeholder="请输入书籍名或者作者名"
              clearable
            ></i-input>
            <Button type="primary" @click="findData">查询</Button>
          </p>
          <Table :columns="columnsList" :data="tableData" :loading="loading"></Table>
          <Page
            class="pager"
            v-if="total > 0"
            :total="total"
            show-total
            show-elevator
            show-sizer
        :page-size="limit"
            @on-change="handlePageChange"
            @on-page-size-change="handlePageSizeChange"
          ></Page>
        </Card>
        <Modal
          class="setting-dialog"
          v-model="isShowModal"
          :title="modalTitle"
          :loading="modalLoading"
          @on-ok="handleModalConfrim"
          @on-cancel="handleModalCancel"
          width="600"
          :mask-closable="false"
        >
          <Form ref="modalForm" :model="modalData" :rules="modalRule" :label-width="150">
            <FormItem prop="bookid" label="书籍名称" :error="modalError.bookid">
              <template v-if="isAddOrUpdateModal === 'add'">
                <Select
                  v-model="modalData.bookid"
                  filterable
                  style="width:240px"
                  placeholder="请选择设置为商品的书籍"
                >
                  <Option
                    v-for="item in allBooks"
                    :value="item._id"
                    :key="item._id"
                  >
                    {{ item.name }}
                  </Option>
                </Select>
              </template>
              <template>
                <span>{{modalData.bookName}}</span>
              </template>
            </FormItem>
            <FormItem prop="type" label="收费类型" :error="modalError.type">
              <Select v-model="modalData.type" filterable style="width:240px" placeholder="请选择收费类型">
                <Option value="1">按章节计费</Option>
                <Option value="2">限时免费</Option>
                <Option value="3">限章节免费</Option>
                <Option value="4">全书免费</Option>
              </Select>
            </FormItem>
            <FormItem
              prop="prise"
              v-if="modalData.type === '1' || modalData.type === '2' || modalData.type === '3'"
              label="价格"
              :error="modalError.prise"
            >
              <i-input
                v-model="modalData.prise"
                placeholder="请输入每一章的价格"
                @on-keyup="numberOnly('prise')"
                style="width:240px"
              ></i-input>
            </FormItem>
            <FormItem
              prop="limit_chapter"
              v-if="modalData.type === '3'"
              label="开始计费章节数"
              :error="modalError.limit_chapter"
            >
              <i-input
                v-model="modalData.limit_chapter"
                placeholder="请输入开始计费章节数"
                @on-keyup="numberOnly('limit')"
                style="width:240px"
              ></i-input>
            </FormItem>
            <FormItem
              prop="limit_date"
              v-if="modalData.type === '2'"
              label="限时免费时间段"
              :error="modalError.limit_date"
            >
              <DatePicker
                v-model="modalData.limit_date"
                type="datetimerange"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择免费时间段"
                style="width: 300px"
              ></DatePicker>
            </FormItem>
          </Form>
        </Modal>
      </i-col>
    </Row>
  </div>
</template>

<script>
import { oldHttp } from "@/utils/http";
import moment from "moment";

export default {
  name: "setting",
  data() {
    return {
      loading: true,
      searchName: "",
      tableData: [],
      allBooks: [],
      total: 0,
      page: 1,
      limit: 10,
      columnsList: [
        {
          title: "序号",
          key: "index",
          width: 80,
          align: "center"
        },
        {
          title: "书籍名称",
          align: "center",
          render: (h, params) => {
            return h(
              "Poptip",
              {
                props: {
                  trigger: "hover",
                  placement: "right",
                  width: "200"
                }
              },
              [
                h("span", params.row.bookid.name),
                h(
                  "div",
                  {
                    class: "book-detail",
                    slot: "content"
                  },
                  [
                    h("img", {
                      class: "book-img",
                      attrs: { src: params.row.bookid.img_url }
                    }),
                    h("p", "书名：" + params.row.bookid.name),
                    h("p", "作者：" + params.row.bookid.author)
                  ]
                )
              ]
            );
          }
        },
        {
          title: "作者",
          align: "center",
          render: (h, params) => {
            return h("span", params.row.bookid.author);
          }
        },
        {
          title: "分类",
          align: "center",
          key: "classify",
          render: (h, params) => {
            if (params.row.bookid.classify instanceof Array && params.row.bookid.classify.length > 0) {
              return params.row.bookid.classify.map(item => h("Tag", item));
            } else if (typeof params.row.bookid.classify === 'string') {
              return <Tag>{params.row.bookid.classify}</Tag>;
            } else {
              return <span>暂无</span>;
            }
          }
        },
        {
          title: "价格",
          align: "center",
          render: (h, params) => {
            return h("span", [h("b", params.row.prise), h("span", " 书币/章")]);
          }
        },
        {
          title: "类型",
          align: "center",
          key: "type",
          render: (h, params) => {
            if (params.row.type === 4) {
              return h("Tag", { props: { color: "green" } }, "全书免费");
            } else if (params.row.type === 3) {
              return h("Tag", { props: { color: "#ef69ff" } }, "章节限免");
            } else if (params.row.type === 2) {
              return h("Tag", { props: { color: "#fb9600" } }, "时间限免");
            } else if (params.row.type === 1) {
              return h("Tag", { props: { color: "blue" } }, "按章计费");
            } else {
              return h("Tag", "未知类型");
            }
          }
        },
        {
          title: "阅读限制",
          align: "left",
          width: 220,
          render: (h, params) => {
            if (params.row.type === 3) {
              return h(
                "span",
                "从第" + (params.row.limit_chapter + 1) + "章开始收费"
              );
            } else if (params.row.type === 2) {
              return h("span", [
                h(
                  "p",
                  "起始时间：" +
                    moment(params.row.limit_start_time).format(
                      "YYYY/MM/DD HH:MM:SS"
                    )
                ),
                h(
                  "p",
                  "结束时间：" +
                    moment(params.row.limit_end_time).format(
                      "YYYY/MM/DD HH:MM:SS"
                    )
                )
              ]);
            } else {
              return h("span", "无");
            }
          }
        },
        {
          title: "创建时间",
          align: "center",
          key: "create_time",
          render: (h, params) => {
            return h(
              "span",
              moment(params.row.create_time).format("YYYY/MM/DD HH:MM:SS")
            );
          }
        },
        {
          title: "操作",
          align: "center",
          width: 200,
          key: "handle",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  class: "change-btn",
                  props: {
                    type: "primary"
                  },
                  on: {
                    click: () => {
                      // 打开修改弹窗
                      this.modalData = {
                        bookid: params.row.bookid._id,
                        bookName: params.row.bookid.name,
                        type: params.row.type.toString(),
                        prise: params.row.prise
                      };
                      if (params.row.limit_chapter) {
                        this.modalData.limit_chapter = params.row.limit_chapter;
                      }
                      if (
                        params.row.limit_start_time &&
                        params.row.limit_end_time
                      ) {
                        this.modalData.limit_date = [
                          new Date(params.row.limit_start_time),
                          new Date(params.row.limit_end_time)
                        ];
                      }
                      this.isShowModal = true;
                      this.modalTitle = "修改商品";
                      this.isAddOrUpdateModal = "update";
                      this.currentGoodId = params.row._id;
                    }
                  }
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error"
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: "温馨提示",
                        content: "确定要删除此商品？",
                        onOk: () => {
                          oldHttp
                            .delete(
                              "/api/admin/good/" + params.row._id,
                              {},
                              "删除商品"
                            )
                            .then(res => {
                              if (res.ok) {
                                // 更新tableData
                                this.isShowModal = false;
                                this.$Message.success("删除商品成功");
                                this.getData();
                              }
                            });
                        },
                        onCancel: () => {}
                      });
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      hasDraged: false,
      isDraging: false, // 处在拖拽状态
      isShowModal: false, // 控制modal的显隐
      modalLoading: true, // 点击modal确定按钮是否显示loading
      modalTitle: "", // modal标题
      isAddOrUpdateModal: "", // 是新增弹窗或者更新弹窗
      currentGoodId: "", // 当前正在修改的商品Id
      modalData: {
        bookid: "",
        type: "",
        prise: "",
        limit_chapter: "",
        limit_date: ""
      },
      modalRule: {
        bookid: [
          { required: true, message: "请输入书籍名称", trigger: "change" }
        ],
        type: [
          { required: true, message: "请输入收费类型", trigger: "change" }
        ],
        prise: [
          // { required: true, message: '请输入每一章价格', trigger: 'change' }
        ],
        limit_chapter: [
          // { required: true, message: '请输入开始计费章节', trigger: 'change' }
        ],
        limit_date: [
          // { required: true, message: '请输入限时免费时间段', trigger: 'blur' }
        ]
      },
      modalError: {} // modal错误提示信息
    };
  },
  methods: {
    // 获取书籍列表
    getAllBooks() {
      return new Promise(resolve => {
        oldHttp.get("/api/admin/book/sign_good", {}, "获取全部书籍列表")
        .then(res => {
          if (res.ok) {
            this.allBooks = res.list;
            resolve(true);
          }
        });
      });
    },
    getData() {
      let self = this;
      self.loading = true;
      oldHttp
        .get(
          "/api/admin/good",
          { page: self.page, limit: self.limit, name: self.searchName },
          "获取商品列表"
        )
        .then(res => {
          self.loading = false;
          if (res.ok) {
            self.tableData = res.list.map((item, index) => {
              item.index = (self.page - 1) * self.limit + index + 1;
              return item;
            });
            self.total = res.total;
          }
        });
    },
    findData() {
      this.limit = 10;
      this.page = 1;
      this.total = 0;
      this.getData();
    },
    // 点击新增商品
    handleAdd() {
      this.getAllBooks().then(() => {
        // 打开新增弹窗
        this.modalData = {
          bookid: "",
          type: "",
          prise: "",
          limit_chapter: "",
          limit_date: ""
        };
        this.isShowModal = true;
        this.modalTitle = "新增商品";
        this.isAddOrUpdateModal = "add";
      });
    },
    handleModalConfrim() {
      let self = this;
      // 合法性校验
      self.$refs["modalForm"].validate(valid => {
        if (valid) {
          let isOk = true;
          let keyReg = /^[A-Za-z0-9_-]+$/;
          let intergeRegExp = /^\d+$/;
          if (!self.modalData.bookid) {
            self.modalError.bookid = Math.random().toString();
            self.$nextTick(function() {
              self.modalError.bookid = "请选择需要添加为商品的书籍";
            });
            isOk = false;
          }
          if (
            self.modalData.type !== "4" &&
            !intergeRegExp.test(self.modalData.prise)
          ) {
            self.modalError.prise = Math.random().toString();
            self.$nextTick(function() {
              self.modalError.prise = "请输入数字形式的价格";
            });
            isOk = false;
          }
          if (
            self.modalData.type === "3" &&
            !intergeRegExp.test(self.modalData.limit_chapter)
          ) {
            self.modalError.limit_chapter = Math.random().toString();
            self.$nextTick(function() {
              self.modalError.limit_chapter = "请输入数字形式的价格";
            });
            isOk = false;
          }
          if (
            self.modalData.type === "2" &&
            (!(self.modalData.limit_date[0] instanceof Date) ||
              !(self.modalData.limit_date[1] instanceof Date))
          ) {
            self.modalError.limit_date = Math.random().toString();
            self.$nextTick(function() {
              self.modalError.limit_date = "限免时间段不合法";
            });
            isOk = false;
          }
          // 如果全部校验通过，发送POST请求
          if (isOk) {
            if (self.isAddOrUpdateModal === "add") {
              // 整理数据格式
              if (self.modalData.type === "2") {
                self.modalData.limit_start_time = self.formatDate(
                  self.modalData.limit_date[0]
                );
                self.modalData.limit_end_time = self.formatDate(
                  self.modalData.limit_date[1]
                );
                delete self.modalData.limit_date;
              }
              self.modalData.prise = self.modalData.prise || 0;
              oldHttp
                .post("/api/admin/good", self.modalData, "新增商品")
                .then(res => {
                  self.modalLoading = false;
                  // 避免校验完直接关闭弹窗
                  self.$nextTick(() => {
                    self.modalLoading = true;
                  });
                  if (res.ok) {
                    self.isShowModal = false;
                    self.$Message.success("新增商品成功");
                    self.getData();
                  }
                })
                .catch(err => {
                  self.modalLoading = false;
                  self.$nextTick(() => {
                    self.modalLoading = true;
                  });
                });
            } else if (self.isAddOrUpdateModal === "update") {
              // 整理数据格式
              if (self.modalData.type === "2") {
                self.modalData.limit_start_time = self.formatDate(
                  self.modalData.limit_date[0]
                );
                self.modalData.limit_end_time = self.formatDate(
                  self.modalData.limit_date[1]
                );
                delete self.modalData.limit_date;
              }
              oldHttp
                .put(
                  "/api/admin/good/" + self.currentGoodId,
                  self.modalData,
                  "修改商品"
                )
                .then(res => {
                  self.modalLoading = false;
                  // 避免校验完直接关闭弹窗
                  self.$nextTick(() => {
                    self.modalLoading = true;
                  });
                  if (res.ok) {
                    self.isShowModal = false;
                    self.$Message.success("修改商品成功");
                    self.getData();
                  }
                })
                .catch(err => {
                  self.modalLoading = false;
                  self.$nextTick(() => {
                    self.modalLoading = true;
                  });
                });
            }
          } else {
            self.modalLoading = false;
            self.$nextTick(() => {
              self.modalLoading = true;
            });
          }
        } else {
          self.modalLoading = false;
          self.$nextTick(() => {
            self.modalLoading = true;
          });
        }
      });
    },
    handleModalCancel() {
      this.$refs["modalForm"].resetFields();
    },
    // 点击分页
    handlePageChange(val) {
      this.page = val;
      this.getData();
    },
    handlePageSizeChange(size) {
      this.limit = size;
      this.getData();
    },
    numberOnly(name) {
      if (name === "prise") {
        this.modalData.prise = parseInt(this.modalData.prise) || 0;
      } else if (name === "limit") {
        this.modalData.limit_chapter =
          parseInt(this.modalData.limit_chapter) || 0;
      }
    },
    formatDate(date) {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();
      return (
        year +
        "/" +
        month +
        "/" +
        day +
        "  " +
        hour +
        ":" +
        minute +
        ":" +
        second
      );
    }
  },
  created() {
    this.getData();
  }
};
</script>

<style lang="less">
.good-container .title {
  height: 32px;
  line-height: 32px;
}
.good-container .add-icon {
  float: right;
}
.good-container .overflow-text {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.good-container .ivu-tooltip-inner {
  max-width: inherit;
}
.good-container .change-btn {
  margin-right: 15px;
}
.good-container .modal-container {
  width: 600px;
  position: absolute;
  left: 50%;
  top: 0;
  margin-left: -300px;
}
.setting-dialog textarea.ivu-i-input {
  font-size: 12px !important;
}
.good-container .pager {
  text-align: right;
  margin-top: 30px;
}
.good-container .book-img {
  width: 50px;
  height: 80px;
  float: left;
  margin-right: 10px;
}
.good-container .book-detail > p {
  text-align: left;
  padding-right: 10px;
}
</style>
